package ajakuulauku;

import java.io.File;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;

public class XMLReader {
	
	Document doc = null;
	ArrayList<XMLElement> elements = new ArrayList<XMLElement>();
	
	public XMLReader(String filename) {
		try {
			File file = new File("levels/"+filename);
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		    dbf.setIgnoringElementContentWhitespace(true);
			doc = dbf.newDocumentBuilder().parse(file);
		}catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	public ArrayList<XMLElement> parse() {
		doc.getDocumentElement().normalize();
		Node root = doc.getFirstChild();
		for(Node element = root.getFirstChild();element != null;){
			Node nextElement = element.getNextSibling();
			if (element.getNodeType() == Node.ELEMENT_NODE) {
				XMLElement tmp = new XMLElement(element.getNodeName());
				for(Node paramElem = element.getFirstChild();paramElem != null;){
					Node nextParamElement = paramElem.getNextSibling();
					if (paramElem.getNodeType() == Node.ELEMENT_NODE) {
						tmp.addParam(paramElem.getNodeName(), paramElem.getFirstChild().getNodeValue());
					}
					paramElem = nextParamElement;
				}
				elements.add(tmp);
			}
			element = nextElement;
		}
		return elements;
	}
}
